<template>
  <el-container style="height: 100vh;">
    <el-aside width="200px">
      <el-input
          style="width: 240px"
          placeholder="Please enter keyword"
          v-model="filterText"
      />
      <el-checkbox
          v-loading="getSectionLoading"
          @change="selectAllSection"
          style="padding:0;margin-right:5px;"
      >全选
      </el-checkbox>
      <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="sectionData.list"
          show-checkbox
          node-key="id"
          highlight-current
          :props="defaultProps"
          :filter-node-method="filterNode"
          @check-change="getCheckedNodes"

      />
    </el-aside>
    <el-container>
      <el-header>
        <!--   搜索     -->
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button type="primary" @click="addCase">添加</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="refreshCase">刷新</el-button>
          </el-form-item>
          <el-form-item label="name">
            <el-input v-model="cases.caseSearchData.name" placeholder="请输入Case Name" clearable/>
          </el-form-item>
          <el-form-item label="section">
            <!--                v-model="cases.caseSearchData.section"-->
            <el-select
                multiple
                clearable
                collapse-tags
                placeholder="暂未实现"
                popper-class="custom-header"
                :max-collapse-tags="1"
                style="width: 240px">
              <!--                @change="selectSectionChange"-->

              <!--              <template #header>-->
              <!--                <el-checkbox-->
              <!--                    v-model="selectAllStatus"-->
              <!--                    :indeterminate="indeterminate"-->
              <!--                    @change="selectAllStatusChange"-->
              <!--                >-->
              <!--                  All-->
              <!--                </el-checkbox>-->
              <!--              </template>-->
              <!--              <el-option-->
              <!--                  v-for="item in sectionData.list"-->
              <!--                  :key="item.id"-->
              <!--                  :label="item.name"-->
              <!--                  :value="item.id"-->
              <!--              />-->

            </el-select>
          </el-form-item>
          <el-form-item label="priority">
            <!--                v-model="cases.caseSearchData.priority"-->
            <el-select
                multiple
                clearable
                collapse-tags
                placeholder="Select"
                popper-class="custom-header"
                :max-collapse-tags="1"
                style="width: 120px">
              <!--                @change="onStatusChange"-->

              <!--              <template #header>-->
              <!--                <el-checkbox-->
              <!--                    v-model="selectAllStatus"-->
              <!--                    :indeterminate="indeterminate"-->
              <!--                    @change="selectAllStatusChange"-->
              <!--                >-->
              <!--                  All-->
              <!--                </el-checkbox>-->
              <!--              </template>-->
              <!--              <el-option-->
              <!--                  v-for="item in allDevStatus"-->
              <!--                  :key="item"-->
              <!--                  :label="item"-->
              <!--                  :value="item"-->
              <!--              />-->
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table :data="cases.list" style="width: 100%" v-loading="getCaseLoading">
          <el-table-column type="expand">
            <template #default="props">
              <div>
                <StepTable :steps="props.row.steps"/>
              </div>
            </template>
            <!--            <StepTable v-for="step in cases.list.steps" :steps="step"/>-->
          </el-table-column>
          <el-table-column prop="name" label="name" width="120"/>
          <el-table-column prop="description" label="des" width="200"/>

          <el-table-column label="section" width="120">

            <template #default="scope">
              <div style="display: flex; align-items: center">

                <span style="margin-left: 10px">{{ scope.row.section.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="priority" width="80"/>
          <el-table-column prop="preCondition" label="pre"/>
          <el-table-column prop="created_at" label="created_at"/>
          <el-table-column prop="updated_at" label="updated_at"/>
        </el-table>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";

import {InitCasesList, InitSectionList} from "@/type/case.ts";
import {apiGetCase, apiGetSection} from "@/request/test_manager/cases.ts";
import StepTable from "@/components/StepTable.vue";
import {showMsg} from "@/plugin/message.ts";

onMounted(() => {
  getSection()
  getCase()
})
// ==========Section Tree==================================================
const filterText = ref('');
const treeRef = ref()
const sectionData = reactive(new InitSectionList())
const defaultProps = {
  children: 'subSections',
  label: 'name',
}
const getSectionLoading = ref(false)
const getSection = async () => {
  const res = await apiGetSection()
  // 避免子节点重复
  sectionData.list = res.results.filter(item => item.parent == null)
  console.log('ad: ', sectionData.list)
}

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
// 获取过滤后的选中节点
const selectedNodes = ref(null)
const getCheckedNodes = () => {
  try {
    getSectionLoading.value = true
    const checkedNodes = treeRef.value.getCheckedNodes(false); // 获取所有完全选中的节点
    selectedNodes.value = checkedNodes.filter((node) => {
      // 如果父节点选中，则过滤所有子节点
      const parent = treeRef.value.getNode(node.id).parent;
      return !parent || !parent.checked;
    });

  } finally {
    getSectionLoading.value = false
  }

};

// 全选，全不选
// const selectAllSectionRef = ref(true)
// 处理全选和全不选
const selectAllSection = (checked) => {
  try {
    getSectionLoading.value = true
    if (checked) {
      const allKeys = getAllNodes(sectionData.list);
      treeRef.value.setCheckedKeys(allKeys);
    } else {
      deselectAll();
    }
  } finally {

    getSectionLoading.value = false
  }

}
// const isAllChecked = () => {
//
//   const checkedKeys = treeRef.value.getCheckedKeys();
//   const totalKeys = sectionData.list.flatMap(node =>
//       [node.id].concat(node.children ? node.children.map(child => child.id) : [])
//   );
//   selectAllSectionRef.value = checkedKeys.length === totalKeys.length;
// }
// 取消全选
const deselectAll = () => {
  treeRef.value.setCheckedKeys([]);
};
const getAllNodes = (nodes) => {
  const keys = [];
  const traverse = (nodeList) => {
    nodeList.forEach((node) => {
      keys.push(node.id);
      if (node.children) traverse(node.children);
    });
  };
  traverse(nodes);
  return keys;
}


// ==========Cases==================================================

const cases = reactive(new InitCasesList())
const getCaseLoading = ref(false)
const getCaseFinishFlag = ref(true)
const getCase = async (params = {}) => {
  try {

    getCaseLoading.value = true
    getCaseFinishFlag.value = false
    // 默认参数
    const defaultParams = {
      page: 1,         // 当前页码
      pageSize: 10,    // 每页数据量
      filter: '',      // 过滤条件
      section_id: null,
    };

    // 合并传入的参数与默认参数
    const finalParams = {...defaultParams, ...params};
    console.log("finalParams: ", finalParams)
    if (finalParams.section_id) {
      const res = await apiGetCase(finalParams)
      cases.list = res.results
    } else {
      cases.list = []
    }
    console.log("cases.list:", cases.list)
  } finally {
    getCaseLoading.value = false
    getCaseFinishFlag.value = true
  }


}
// ==========搜索栏==================================================

const addCase = async () => {
  showMsg(1, '暂未支持', true, 5)
}

const refreshCase = () => {
  const sectionIds = selectedNodes.value?.map(section => section.id).join(',');
  getCase({section_id: sectionIds})
}

// section 选择状态
const selectSectionChange = () => {


}
// ==========Tree <=> Table=========================================
// todo section 全选操作太快会导致Tree与Table不同步
watch(() => selectedNodes.value, (newValue) => {
      // 提取 id 生成 section_id 列表
      console.log("selectedNodes newValue：", newValue);
      const sectionIds = newValue?.map(section => section.id).join(',');
      console.log("sectionIds", sectionIds); // 输出: [1, 2, 3]
      getCase({section_id: sectionIds})
    }
)

watch(() => getCaseFinishFlag.value, (value) => {
  if (value) {
    console.log("getCaseFinishFlag:", value)
    getSectionLoading.value = false
    getCaseLoading.value = false
  } else {
    getSectionLoading.value = true
    getCaseLoading.value = true
  }
})

</script>

<style scoped>

</style>